<template>
  <div class="CustomQuota">
    <el-row>
      <!-- 第一步 -->
      <div>
        <el-row>
          <el-col :span="7" style="padding: 20px 30px 0 30px">
            <div class="grid-content bg-purple-dark">
              <div
                class="grid-content themeTree"
                style="border: 1px solid #dfe4ed; height: 550px"
              >
                <themeTree
                  @themeNode="handleCurrentChange"
                  :showcheckbox="false"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="16"
          >
            <div>
              <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="指标 / 维度" name="first">
                  <el-row class="quota">
                    <el-col :span="11" style="padding-left: 20px">
                      <div class="grid-content bg-purple-dark">
                        <div class="Quota">
                          <el-form
                            ref="newQuotaForm1"
                            :rules="first.rules"
                            :model="first.newQuotaForm"
                            label-width="100px"
                          >
                            <el-form-item label="所属主题" prop="themeTitle">
                              <el-input
                                disabled
                                placeholder="请在左侧选择主题"
                                v-model="first.newQuotaForm.themeTitle"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标名称" prop="name">
                              <el-input
                                v-model="first.newQuotaForm.name"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标简称" prop="uname">
                              <el-input
                                v-model="first.newQuotaForm.uname"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标描述" prop="description">
                              <el-input
                                v-model="first.newQuotaForm.description"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标代码" prop="code">
                              <el-input
                                v-model="first.newQuotaForm.code"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标标签" prop="lable">
                              <el-input
                                v-model="first.newQuotaForm.lable"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="指标类型" prop="type">
                              <el-select
                                class="quotaType"
                                v-model="first.newQuotaForm.type"
                                placeholder="请选择指标类型"
                              >
                                <el-option
                                  v-for="item in first.quotaType"
                                  :key="item.label"
                                  :label="item.value"
                                  :value="item.label"
                                ></el-option>
                              </el-select>
                            </el-form-item>
                            <el-form-item label="指标值" prop="quotaValue">
                              <el-input
                                placeholder="请填写指标值"
                                v-model="first.newQuotaForm.quotaValue"
                              ></el-input>
                            </el-form-item>
                            <el-form-item label="度量值" prop="measureValue">
                              <el-input
                                placeholder="请填写度量值"
                                v-model="first.newQuotaForm.measureValue"
                              ></el-input>
                            </el-form-item>
                          </el-form>
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12" style="padding: 20px 20px 0 70px"
                    >
                      <div
                        class="dTree"
                        style="border: 1px solid #dfe4ed; height: 415px"
                      >
                        <div
                          style="
                            text-align: center;
                            border: 1px solid #dfe4ed;
                            line-height: 30px;
                            color: #606266;
                          "
                        >
                          请选择维度
                        </div>
                        <el-tree
                          ref="dTree"
                          :check-strictly="true"
                          :data="second.dimensionList"
                          :props="second.props"
                          @check-change="handleCheckChange"
                          show-checkbox
                          :accordion="true"
                          node-key="id"
                        >
                        </el-tree>
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <div style="text-align: right;margin-top:18px;padding-right:66px">
                        <el-button type="primary" @click="resetFrom()"
                        >重置
                        </el-button>
                        <el-button type="primary" @click="submitFrom()">
                          提交
                        </el-button>
                      </div>
                    </el-col>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col
          >
        </el-row>
        <el-row v-show="showQuotaTable">
          <el-col>
            <div class="app-container">
              <el-table
                :data="tableData"
                height="250"
                border
                style="width: 100%"
              >
                <el-table-column
                  is="false"
                  prop="id"
                  label="序号"
                  align="center"
                  width="100"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="name"
                  label="预指标名称"
                  align="center"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="uname"
                  align="center"
                  label="预指标简称"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="code"
                  align="center"
                  label="预指标代码"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="themeSetTitle"
                  align="center"
                  label="预指标所属主题"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="dimensionNames"
                  align="center"
                  label="维度集合"
                ></el-table-column>
                <el-table-column
                  prop="measure"
                  align="center"
                  label="度量值"
                ></el-table-column>
                <el-table-column
                  prop="value"
                  align="center"
                  label="指标值"
                ></el-table-column>
                <el-table-column prop="av" align="center" label="平均值">
                  <template slot-scope="{row}">
                    <span>{{ row.av ? row.av : 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="ct" align="center" label="计数">
                  <template slot-scope="{row}">
                    <span>{{ row.ct ? row.ct : 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="mx" align="center" label="最大值">
                  <template slot-scope="{row}">
                    <span>{{ row.mx ? row.mx : 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="mn" align="center" label="最小值">
                  <template slot-scope="{row}">
                    <span>{{ row.mn ? row.mn : 0 }}</span>
                  </template>
                </el-table-column>

                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="updateDate"
                  align="center"
                  label="更新时间"
                ></el-table-column>
              </el-table>
              <pagination
                v-show="totalCount > 0"
                :total="totalCount"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="loadDefineList"
              />
            </div>
          </el-col>
        </el-row>
        <el-row v-show="showBtn" style="margin:0 0 10px 30px">
          <el-button type="primary" @click="backStep">
            上一步
          </el-button>
        </el-row>
      </div>
    </el-row>
  </div>
</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
  import DimensionTree from '@/views/quota/modeling/DimensionTree.vue'
  import themeTree from '@/views/quota/reportUpload/themeTree.vue'
  import { listCtSet } from '@/api/quota/theme_zone/zone'
  import { listDimension } from '@/api/metadata/dimension'
  import { getDefineList, queryQuotaType, saveCustomQuota } from '@/api/quota/define/define.js'

  export default {
    name: 'CustomQuota',
    //使用import引入外部组件需要在components对象中注册才可以使用
    components: { themeTree, DimensionTree },
    props: {
      showQuotaTable: {
        type: Boolean,
        default: true
      },
      showBtn: {
        type: Boolean,
        default: false
      },
      quotaCreateType: {
        type: Number,
        default: 2
      },
      sql: {
        type: String,
        default: ''
      },
      datasourceId: {
        type: Number,
        default: undefined
      },
      propMeasureCol: {
        type: String,
        default: ''
      }

    },
    data() {
      //这里存放数据
      return {
        activeName: 'first',
        stepActive: 0,
        tableHighlight: false,
        tableData: [],
        totalCount: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          orderField: 'UPDATE_DATE',
          order: 'desc',
          createType: this.quotaCreateType,
          themeId: null
        },
        first: {
          fromCheckRst: false,
          themeData: [],
          themeQueryParams: {
            pageNum: 0,
            pageSize: 100000
          },
          newQuotaForm: {
            themeTitle: null,
            description: null,
            measureCol: this.propMeasureCol,
            lable: null,
            name: null,
            type: null,
            sType: '5',
            uname: null,
            code: null,
            themeSetId: null,
            parentId: 0,
            datasourceId: null,
            createType: this.quotaCreateType,
            qsql: '',
            rootNodeId: [],
            //属性为维度id 属性值为维度id的根节点id
            dimMap: {},
            childrenNodeId: [],
            rootNodeName: [],
            childrenNodeName: [],
            measureValue: null,
            quotaValue: null
          },
          rules: {
            description: [
              { required: true, message: '请输入预指标描述', trigger: 'blur' }
            ],
            lable: [
              { required: true, message: '请输入预指标标签', trigger: 'blur' }
            ],
            themeTitle: [
              { required: true, message: '请选择所属主题', trigger: 'blur' }
            ],
            name: [
              { required: true, message: '请输入预指标名称', trigger: 'blur' }
            ],
            type: [
              { required: true, message: '请选择预指标类型', trigger: 'blur' }
            ],
            uname: [
              { required: true, message: '请输入预指标简称', trigger: 'blur' }
            ],
            code: [
              { required: true, message: '请输入预指标代码', trigger: 'blur' }
            ],
            quotaValue: [
              { required: true, message: '请输入预指标值', trigger: 'blur' }
            ],
            measureValue: [
              { required: true, message: '请输入度量值', trigger: 'blur' }
            ]
          },
          quotaType: []
        },
        second: {
          dimensionList: [],
          props: {
            label: 'dimensionName',
            children: 'children',
            hasChildren: 'hasChildren'
          },
          queryParams: {
            current: 1,
            size: 10000
          }
        }
      }
    },
    //计算属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {
      sql(newVal, oldVal) {
        this.first.newQuotaForm.qsql = newVal
      },
      propMeasureCol(newVal, oldVal) {
        this.first.newQuotaForm.measureCol = newVal
      },
      quotaCreateType(newVal, oldVal) {
        this.first.newQuotaForm.createType = newVal
        this.queryParams.createType = newVal
      }
    },
    //方法集合
    methods: {
      //回退到上一步
      backStep() {
        this.$emit('backStep')
      },
      resetFrom() {
        this.$refs['newQuotaForm1'].resetFields()
        this.first.fromCheckRst = false
        this.$refs.dTree.setCheckedKeys([])
        this.loadDefineList()
      },
      submitFrom() {
        this.$refs['newQuotaForm1'].validate((valid) => {
          if (valid) {
            this.$confirm('提交后不可修改，确定提交吗？', '提示', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning'
            })
              .then(() => {
                this.first.newQuotaForm.datasourceId = this.datasourceId
                saveCustomQuota(this.first.newQuotaForm).then((res) => {
                  if (res.data) {
                    this.$message({
                      message: '数据已提交',
                      type: 'success'
                    })
                    this.stepActive = 0
                    this.resetFrom()
                    this.$refs.dTree.setCheckedKeys([])
                    this.loadDefineList()
                  }
                })
              })
              .catch(() => {
              })
          }
        })
      },
      checkQuotaFrom() {
        this.$refs['newQuotaForm1'].validate((valid) => {
          if (valid) {
            this.first.fromCheckRst = true
          }
        })
      },
      handleCurrentChange(val) {
        this.input = '当前选择的主题为"' + val.name + '"'
        this.first.newQuotaForm.themeTitle = val.name
        this.first.newQuotaForm.themeSetId = val.id
        this.queryParams.themeId = val.id
        const h = this.$createElement
        this.$notify({
          title: '提示',
          message: h('i', { style: 'color: teal' }, this.input)
        })
        this.loadDefineList()
      },
      getListZone() {
        listCtSet(this.first.themeQueryParams).then((res) => {
          this.first.themeData = res.data.list
          this.first.themeTotalCount = res.data.totalCount
        })
      },
      getListDimension() {
        this.loading = true
        this.second.queryParams.activeYear = new Date().getFullYear()
        listDimension(this.second.queryParams).then((response) => {
          this.second.dimensionList = this.handleTree(
            response.data.records,
            'id',
            'upperId'
          )
          this.loading = false
        })
      },
      nextStep() {
        if (this.stepActive == 0) {
          this.checkQuotaFrom()
          if (!this.first.fromCheckRst) {
            this.$message({
              message: '请检查表单项是否填写完成',
              type: 'warning'
            })
            this.first.fromCheckRst = false
            return
          }
        }
        if (this.stepActive == 1) {
          if (this.first.newQuotaForm.childrenNodeId == null) {
            this.$message({
              message: '请选择要关联的维度',
              type: 'warning'
            })
            return
          }
        }
        this.stepActive++
      },
      previousStep() {
        this.stepActive--
      },
      //树选择
      handleCheckChange(data, flag, childrenFlag) {
        //只有选中状态下才操作数据
        let rootNode = data
        if (data.upperId != 0) {
          rootNode = this.getRootNode(data.upperId).data
        }

        if (flag) {
          this.first.newQuotaForm.rootNodeName.push(rootNode.dimensionName)
          this.first.newQuotaForm.childrenNodeName.push(data.dimensionName)
          this.first.newQuotaForm.dimMap[data.id + ''] = rootNode.id
        } else {
          this.first.newQuotaForm.rootNodeName.splice(
            this.first.newQuotaForm.rootNodeName.indexOf(
              rootNode.dimensionName,
              1
            )
          )
          this.first.newQuotaForm.childrenNodeName.splice(
            this.first.newQuotaForm.childrenNodeName.indexOf(
              data.dimensionName,
              1
            )
          )
          this.$delete(this.first.newQuotaForm.dimMap, data.id + '')
        }
        console.log(
          'this.first.newQuotaForm.dimMap',
          this.first.newQuotaForm.dimMap
        )
      },
      getRootNode(key) {
        let node = this.$refs.dTree.getNode(key)
        if (node.data.upperId === 0) {
          return node
        }
        key = node.data.upperId
        return this.getRootNode(key)
      },
      //加载指标数据
      loadDefineList() {
        getDefineList(this.queryParams).then((res) => {
          this.tableData = res.data.list
          this.totalCount = res.data.totalCount
        })
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.getListZone()
      this.getListDimension()
      this.loadDefineList()
      queryQuotaType().then((res) => {
        this.first.quotaType = res.data

      })
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
    },
    beforeCreate() {
    }, //生命周期 - 创建之前
    beforeMount() {
    }, //生命周期 - 挂载之前
    beforeUpdate() {
    }, //生命周期 - 更新之前
    updated() {
    }, //生命周期 - 更新之后
    beforeDestroy() {
    }, //生命周期 - 销毁之前
    destroyed() {
    }, //生命周期 - 销毁完成
    activated() {
    } //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
<style lang="less">
  .CustomQuota {
    .el-form {
      margin-top: 20px;
    }

    .el-tabs {
      margin-top: 20px;
      height: 508px;
    }

    .el-tabs__nav-wrap {
      border-bottom: 1px solid #dfe4ed;
    }

    .el-form-item {
      margin-bottom: 10px;
    }

    .el-tabs__content {
      border: 1px solid #dfe4ed;
      height: 100%;
      overflow: auto;
    }

    .el-tabs__header {
      margin: 0;
    }

    .dialog-footer {
      text-align: right;
    }

    .dTree {
      overflow: auto;
    }

    .themeTree {
      overflow: auto;
    }

    .el-tree {
      display: inline-block;
    }

    .el-table__body tr.current-row > td {
      background-color: #6eadff !important;
      color: #fff;
    }

    .quotaType {
      width: 100%;
    }

    .div-center {
      position: absolute;
      width: 100px;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }
</style>
